//
//  WBUserAccount.swift
//  SwiftWeibo
//
//  Created by Lausen on 2017/4/19.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit

private let accountFile: NSString = "userAccount.json"

class WBUserAccount: NSObject {

    /// 用户的令牌
    var access_token: String?
    
    /// 获取到的appkey
    var uid: String?
    
    /// 用户的大头像的连接
    var avatar_large: String?
    
    /// 用户的名字
    var screen_name: String?
    
    ///过期时间
    var expires_in: TimeInterval = 0{
        
        didSet{
            
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    override init() {
        super.init()
        
        //1:获取文件路径
        guard let filePath = accountFile.cz_appendDocumentDir(),
              let data = NSData(contentsOfFile: filePath),
              let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: Any]
            else{
                
            return
        }
    
        //2:使用字典加载属性
        yy_modelSet(with: dict ?? [:])
        
        //3:账户过期的处理
//        expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
        
        if expiresDate?.compare(Date()) == .orderedAscending {
            
            //1:清理token
            access_token = nil
            //2:清理uid
            uid = nil
            
            //3:删除磁盘里面存储的数据
            try? FileManager.default.removeItem(atPath: filePath)
        }
    }
    
    /// 账号到期的时间
    var expiresDate: Date?
    
    override var description: String{
        
        return yy_modelDescription()
    }
    
}


extension WBUserAccount{
    
    func  saveUserAccount() {
        //保存到磁盘去
        //1:将模型转化成字典
        var dict = self.yy_modelToJSONObject() as? [String: Any] ?? [:]
        
        //2:去掉expires_in
        _ = dict.removeValue(forKey: "expires_in")
        
        //3:转换成data
        guard let data = try? JSONSerialization.data(withJSONObject: dict , options: []),
              let filePath = accountFile.cz_appendDocumentDir()
        else{
            
            return
        }
        
        print("磁盘地址\(filePath)")
        
        (data as NSData).write(toFile: filePath, atomically: true)
    }
}
